package com.filex.ads.common;

import android.content.Context;
import android.graphics.Point;
import android.text.TextUtils;

import com.filex.ads.FilexAd;
import com.filex.ads.RequestParams;
import com.filex.ads.network.Networking;


public class AdUrlGenerator extends BaseUrlGenerator {

    protected Context mContext;
    protected AdFormat mAdFormat;
    protected RequestParams mRequestParams;

    public AdUrlGenerator(Context context) {
        mContext = context;
    }

    public AdUrlGenerator withAdFormat(AdFormat adFormat) {
        mAdFormat = adFormat;
        return this;
    }

    public AdUrlGenerator withRequestParams(RequestParams requestParams) {
        mRequestParams = requestParams;
        return this;
    }

    protected void addBaseParams(final ClientMetadata clientMetadata) {
        setAdFormat(mAdFormat.toString());
        setDeviceType();
        setDeviceManufacturer(clientMetadata.getDeviceManufacturer());
        setModel(clientMetadata.getDeviceModel());
        setOS();
        setOSVersion(clientMetadata.getDeviceOsVersion());
        setSdkVersion(clientMetadata.getSdkVersion());
        setCarrierName(clientMetadata.getNetworkOperatorName());
        setNetworkType(clientMetadata.getActiveNetworkType().toString());
        setBundleId(clientMetadata.getAppPackageName());
        setAppVersion(clientMetadata.getAppVersion());
        setUserAgent(Networking.getUserAgent(mContext.getApplicationContext()));
        GpsHelper.AdvertisingInfo advertisingInfo = Networking.getAdvertisingInfo();
        String gaid = advertisingInfo != null ? advertisingInfo.advertisingId : "";
        if (TextUtils.isEmpty(gaid)) {
            gaid = FilexSPHelper.getString(mContext.getApplicationContext(), "gaid", "");
        }
        setGAID(gaid);
        if (FilexAd.isTestMode()) {
            setTestMode(true);
        }
        if (mRequestParams != null) {
            setDeviceDimensions(new Point(mRequestParams.getWidth(), mRequestParams.getHeight()));
        } else {
            setDeviceDimensions(clientMetadata.getDeviceDimensions());
        }
    }


    @Override
    public String generateUrlString(String placementId) {
            initUrlString(placementId);
            ClientMetadata clientMetadata = ClientMetadata.getInstance(mContext);
            addBaseParams(clientMetadata);
            return getFinalUrlString();
        }
}
